<?php

class attachmentsTask extends sfBaseTask
{
  protected function configure()
  {
    // // add your own arguments here
    // $this->addArguments(array(
    //   new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
    // ));

    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
      // add your own options here
    ));
    
    $this->namespace        = 'loan';
    $this->name             = 'loanStatus';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [attachments|INFO] task does things.
Call it with:
auto
  [php symfony attachments|INFO]
EOF;
  }
 
   protected function execute($arguments = array(), $options = array()){
     $databaseManager = new sfDatabaseManager($this->configuration);
     $connection = $databaseManager->getDatabase($options['connection'])->getConnection();
     
     $loans = Doctrine::getTable('Loan')->findByStatus(1);
     
     foreach($loans as $loan){
        
        $start_time = strtotime($loan->getCreatedAt());
        $end_time = $start_time + ( $loan->getEndTime() * 86400);
        $current_time = time();
        
        if($end_time < $current_time ){
          
           $fail_record = new LoanFailRecord();
           $fail_record->setLoanId($loan->getId())->setLoanUserId($loan->getUserId())
                       ->setActionUserType(0)->setActionUserId(0)->setActionType(1)->setStatus(0)->save();
           
           $all_user = Doctrine::getTable('LoanRecord')->createQuery()
                                                        ->where('loan_id = ?',$loan->getId())
                                                        ->andWhere('status = ?',0)
                                                        ->execute();
            foreach($all_user as $user_loan_record){
                $user_money = $user_loan_record->getLoanMoney();
                $user_account_money_change = new AccountMoneyChangeRecord();
                $user_account_money_change->setUserId($user_loan_record->getUserId())
                                          ->setCurrentMoney($user_money)
                                          ->setActionType(AccountMoneyChangeRecord::LIUBIAO)
                                          ->save();
                $user_loan_record->setStatus(2)->save();
            }
            $user_account = Doctrine::getTable('UserAccount')->findOneByUserId($loan->getUserId());
            $user_account->computeFailedLoanQuota($loan->getMoney())->save();
            $loan->setStatus(Loan::LIUBIAO)->setRemainder(0)->save();
            $fail_record->setStatus(1)->save();
        }
     }
   }

}
